<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="true"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <div class="filterBox">
        <el-row class="searchInputWidth">
          <el-form :inline="true" :model="filterField">
            <el-form-item label="" class="row-padding-bottom">
              <el-input
                v-model="filterField.projectName"
                placeholder="请输入项目名称"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="" class="row-padding-bottom">
              <el-cascader
                ref="manageArea"
                v-model="areaId"
                :options="areasOptions"
                @change="getAreaId"
                clearable
                filterable
                :props="{ checkStrictly: true }"
                placeholder="请选择区域"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="" class="row-padding-bottom">
              <el-select
                class="selectWidth"
                v-model="filterField.industryId"
                filterable
                placeholder="请选择行业"
                clearable
              >
                <el-option
                  v-for="item in industryOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" class="row-padding-bottom">
              <el-select
                v-model="filterField.status"
                class="baseSearchItem"
                placeholder="请选择开工状态"
                clearable
                filterable
              >
                <el-option
                  v-for="item in statusOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" class="row-padding-bottom">
              <el-select
                placeholder="请选择投资类别"
                v-model="filterField.investment"
                class="baseSearchItem"
                clearable
                filterable
              >
                <el-option
                  v-for="item in investmentOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" class="row-padding-bottom">
              <el-select
                placeholder="请选择项目清洗"
                v-model="filterField.cleanId"
                class="baseSearchItem"
                clearable
                filterable
              >
                <el-option
                  v-for="item in washtypeOptions"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" class="row-padding-bottom">
              <timeSelection
                @getStartTimeValue="getStartTimeValue"
                @getEndTimeValue="getEndTimeValue"
                :startTimeTitle="startTimeTitle"
                :endTimeTitle="endTimeTitle"
              ></timeSelection>
            </el-form-item>
            <el-form-item label="" class="row-padding-bottom">
              <timeSelection
                @getStartTimeValue="getStartTimeValueTwo"
                @getEndTimeValue="getEndTimeValueTwo"
                :startTimeTitle="startTimeTitleTwo"
                :endTimeTitle="endTimeTitleTwo"
              ></timeSelection>
            </el-form-item>
            <el-form-item class="searchBut">
              <!-- <el-button type="primary" icon="icon iconfont iconchazhao1" @click="searchList" class="commonBtn"></el-button> -->
              <el-button
                type="primary"
                icon="icon iconfont iconchazhao1"
                @click="searchList"
                class="searchBtn"
              >
                <span>搜索</span>
              </el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div class="spacing"></div>
      <!-- 20210423 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
        type="card"
        class="commonTab"
      >
        <el-tab-pane label="详细情况" name="first"></el-tab-pane>
        <el-tab-pane label="项目分布" name="second"></el-tab-pane>
      </el-tabs>
      <!-- 详细情况 -->
      <div class="proDetailsListBox" v-show="activeName == 'first'">
        <div class="colSetupBottom">
          <el-button
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icondaochu"
            @click="getExportList"
          >
            <span class="opetareText">导出报表</span>
          </el-button>
        </div>
        <!-- 表格 -->
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
          stripe
          ref="table"
          highlight-current-row
          :max-height="tableHeight"
        >
          <el-table-column
            :min-width="
              item.prop === 'projectName' ||
              item.prop === 'pbName' ||
              item.prop === 'pcName' ||
              item.prop === 'address'
                ? 230
                : 200
            "
            :label="item.label"
            :property="item.prop"
            v-for="item in headerList"
            :key="item.id"
            default-expand-all
            :fixed="item.prop === 'projectName'"
            v-if="item.isShow"
            :formatter="formatTd"
          >
            <template slot-scope="scope">
              <div v-if="item.prop == 'projectName'">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row[scope.column.property]"
                  :columnName="'projectName'"
                ></copyText>
              </div>
              <div v-else-if="item.prop == 'pbName'">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row[scope.column.property]"
                  :columnName="'pbName'"
                ></copyText>
              </div>
              <div v-else-if="item.prop == 'pcName'">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row[scope.column.property]"
                  :columnName="'pcName'"
                ></copyText>
              </div>
              <div v-else-if="item.prop == 'address'">
                <copyText
                  :tableIndex="scope.$index"
                  :copyTextName="scope.row[scope.column.property]"
                  :columnName="'address'"
                ></copyText>
              </div>
              <div v-else>
                <span>{{
                  scope.row[scope.column.property] !== 0
                    ? scope.row[scope.column.property] || '--'
                    : 0
                }}</span>
              </div>
            </template>
            <template slot="header" slot-scope="scope">
              <span>{{ item.label }}</span>
              <el-tooltip
                class="item"
                effect="dark"
                placement="top-start"
                v-if="checkProps(item.prop)"
              >
                <i class="el-icon-warning" size="18"></i>
                <span slot="content" v-if="item.prop == 'realNameTotal'">
                  项目累计录入的实名制总人数，以身份证号去重
                </span>
                <span slot="content" v-if="item.prop == 'isSaDesc'">
                  项目录入了工资专户，即代表开设了专户
                </span>
                <span slot="content" v-if="item.prop == 'psMonthTotal'">
                  项目所有工资表中，代发到账时间在当前<br />
                  自然月1号至当前日期的代发人次之和
                </span>
                <span slot="content" v-if="item.prop == 'saMonthTotal'">
                  项目所有工资表中，代发到账时间在当前<br />
                  自然月1号至当前日期的代发金额之和
                </span>
                <span
                  slot="content"
                  v-if="item.prop == 'lastCreateSalaryTableDate'"
                >
                  以工资表是发的哪个月的工资作为比对，比如目前<br />
                  创建的发薪年月最大的工资表是2020年9月第一批次<br />
                  的工资表，则最近制作工资表月份是2020年9月
                </span>
                <span slot="content" v-if="item.prop == 'lastSalaryArriveDate'">
                  以工资表是发的哪个月的工资作为比对，比如目前状<br />
                  态为【已发放】工资表中，发薪年月最大的工资表是<br />
                  2020年9月第一批次，则最近发薪到账月份是2020年9月
                </span>
              </el-tooltip>
            </template>
          </el-table-column>
          <!-- 固定列 -->
          <!-- :fixed ="item.prop == 'projectName' ? true : false" -->
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关数据"></emptyTable>
          </div>
        </el-table>
        <!-- 分页 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          style="height: 52px"
        ></Pagination>
      </div>
      <!-- 项目分布 -->
      <div class="chartBox" v-show="activeName == 'second'">
        <div class="chartBoxTotal">
          满足查询条件的，共计{{ projectTotal }}个项目
        </div>
        <div class="secondaryTitle secondaryTitleTheme">项目按照地区分布</div>
        <div id="areaChart" style="height: 300px"></div>
        <div class="secondaryTitle secondaryTitleTheme">项目按照行业分布</div>
        <div id="industryChart" style="height: 300px"></div>
      </div>
    </div>
    <exportExcel
      :colmnList="exportTableCol"
      :mark="mark"
      @getExportList="getExportList"
      v-if="isShowDialog"
      :dialogFormVisible="isShowExcel"
      @closeDialog="hiddenDialog"
    ></exportExcel>
    <el-dialog
      title="正在生成数据，请稍后"
      :visible.sync="dialogVisible"
      width="400px"
      :close-on-click-modal="false"
      :show-close="false"
      class="loadData"
    >
      <el-progress
        :percentage="percentage"
        :color="customColor"
        :show-text="false"
      ></el-progress>
    </el-dialog>
  </div>
</template>
<script>
import exportExcel from '@/components/publicCom/exportExcel'
import common from '../../kits/common'
import { mapActions, mapState } from 'vuex'
import { drarProjectChart } from '../../kits/charts'
export default {
  name: 'diyTableD',
  components: {
    exportExcel,
  },
  data() {
    return {
      tableHeight: null,
      titleText: '项目明细报表',
      showExcel: false,
      headerList: [], //列表头部数据
      tableList: [], //列表数据
      filterField: {
        areaId: '',
        industryId: '',
        status: '',
        investment: '',
        effectiveStartDate: '',
        effectiveEndDate: '',
        params: [],
        splicingType: 'and',
        startDate: '',
        searchDate: '',
        projectName: '',
        cleanId: '',
      },
      startTimeTitle: '建档开始日期',
      endTimeTitle: '建档结束日期',
      startTimeTitleTwo: '开工开始日期',
      endTimeTitleTwo: '开工结束日期',
      paramsList: [],
      date: '',
      startDate: '',
      loading: true,
      isShow: false, //列表加载
      percentage: 0,
      customColor: '#409eff',
      dialogVisible: false,
      startPro: '',
      requestUrl: 'api-s/cs/projectstats/base/find ',
      areaId: '', //区域
      mark: 'projectDetailReport',
      exportTableCol: [], //导出报表数据
      colSetupTableTotle: [],
      isShowDialog: false,
      isShowExcel: false,
      washtypeOptions: [],
      activeName: 'first',
      projectTotal: 0,
    }
  },
  computed: {
    ...mapState([
      'investmentOptions',
      'statusOptions',
      'areasOptions',
      'industryOptions',
    ]),
    filterHeaderList() {
      return this.headerList.filter((item) => {
        return item.isShow
      })
    },
  },
  created() {
    if (this.$store.state.userType == 'FINANCE') {
      this.$store.commit('SET_INFO', [
        'investmentOptions',
        [{ id: 'GOV', name: '政府投资' }],
      ])
    } else {
      this.getInvestmenttype({})
    }
    this.getStatus({})
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getIndustry({})
    this.getWashtype()
  },
  mounted() {
    this.titleText = this.$route.query.title
    this.getSettingDetail(this.$route.query.id)
    this.$nextTick(function () {
      this.tableHeight = window.innerHeight - 296
      // 监听窗口大小变化
      let self = this
      window.onresize = function () {
        self.tableHeight = window.innerHeight - 296
      }
    })
  },
  activated() {
    // this.titleText = this.$route.query.title
    // this.getSettingDetail(this.$route.query.id)
  },
  methods: {
    checkProps(val) {
      if (
        val == 'realNameTotal' ||
        val == 'isSaDesc' ||
        val == 'psMonthTotal' ||
        val == 'saMonthTotal' ||
        val == 'lastCreateSalaryTableDate' ||
        val == 'lastSalaryArriveDate'
      ) {
        return true
      }
      return false
    },
    searchList() {
      var that = this
      that.dialogVisible = true
      that.percentage = 0
      that.paramsList.forEach(function (element, index) {
        for (var key in element) {
          if (element.name == '') {
            that.paramsList.splice(index, 1)
          }
        }
      })
      this.isShowAdd = true
      var paramsList = that.packageParams(that.paramsList)
      that.filterField.params = paramsList
      if (this.activeName == 'second') {
        this.axios
          .post('api-s/cs/projectstats/base/projectStats', that.filterField)
          .then((res) => {
            if (!res.data.hasError) {
              const { area, industry, total } = res.data.result
              this.projectTotal = total
              let datas1 = []
              let datas2 = []
              area.forEach((item) => {
                datas1.push([item.areaName, item.amount])
              })
              industry.forEach((item) => {
                datas2.push([item.industryName, item.amount])
              })
              this.$nextTick(() => {
                drarProjectChart('#48A1FF', 'areaChart', datas1)
                drarProjectChart('#03CB94', 'industryChart', datas2)
              })
            }
          })
      }
      that.startPro = setInterval(function () {
        that.percentage += 30
        if (that.percentage > 70) {
          clearInterval(that.startPro)
          that.$nextTick(function () {
            that.$refs.pagination.getTableListData()
          })
        }
      }, 50)
    },
    getSettingDetail(reportId) {
      this.axios
        .get('api-s/cs/projectstats/customreport/detail', {
          params: { reportId },
        })
        .then((res) => {
          if (!res.data.hasError) {
            const { conditionVOS, dimensionVOS } = res.data.result
            this.paramsList = conditionVOS
            this.headerList = []
            dimensionVOS.forEach((item) => {
              item.children.forEach((m) => {
                if (m.isShow) {
                  this.headerList.push(m)
                }
              })
            })
            this.searchList()
          }
        })
    },
    goBack() {
      this.$router.push('/home/statement/diyTable')
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/statement/diyTable',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    /**
     * @description: 获取开始日期
     * @param {*} urls
     * @param {*} datas
     */
    getStartTimeValue(val) {
      if (val) {
        this.filterField.effectiveStartDate = val
      } else {
        this.filterField.effectiveStartDate = ''
      }
    },
    /**
     * @description: 获取结束日期
     * @param {*} urls
     * @param {*} datas
     */
    getEndTimeValue(val) {
      if (val) {
        this.filterField.effectiveEndDate = val
      } else {
        this.filterField.effectiveEndDate = ''
      }
    },
    /**
     * @description: 获取开始日期
     * @param {*} urls
     * @param {*} datas
     */
    getStartTimeValueTwo(val) {
      if (val) {
        this.filterField.startDate = val
      } else {
        this.filterField.startDate = ''
      }
    },
    /**
     * @description: 获取结束日期
     * @param {*} urls
     * @param {*} datas
     */
    getEndTimeValueTwo(val) {
      if (val) {
        this.filterField.searchDate = val
      } else {
        this.filterField.searchDate = ''
      }
    },
    ...mapActions([
      'getInvestmenttype',
      'getStatus',
      'getAreas',
      'getIndustry',
    ]),
    getTableList(data) {
      this.percentage = 100
      var that = this
      setTimeout(function () {
        that.dialogVisible = false
      }, 200)
      this.tableList = data
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    toExportExcel() {
      this.isShowDialog = true
      this.isShowExcel = true
    },
    hiddenDialog(val) {
      this.isShowDialog = false
      this.isShowExcel = false
    },
    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.filterField.areaId = areaId
    },

    // 导出报表
    getExportList(val) {
      var fieldArr = []
      for (var i = 0; i < this.headerList.length; i++) {
        if (this.headerList[i].isShow == true) {
          fieldArr.push(this.headerList[i].prop)
        }
      }
      fieldArr = fieldArr.join(',')
      const vm = this
      vm.paramsList.forEach(function (element, index) {
        for (var key in element) {
          if (element.name == '') {
            vm.paramsList.splice(index, 1)
          }
        }
      })
      var paramsList = encodeURIComponent(vm.packageParams(vm.paramsList))
      if (this.tableList.length > 0) {
        window.location.href =
          common.commonApi +
          'api-s/cs/projectstats/base/export?areaId=' +
          vm.filterField.areaId +
          '&industryId=' +
          vm.filterField.industryId +
          '&investment=' +
          vm.filterField.investment +
          '&status=' +
          vm.filterField.status +
          '&projectName=' +
          vm.filterField.projectName +
          '&effectiveStartDate=' +
          vm.filterField.effectiveStartDate +
          '&effectiveEndDate=' +
          vm.filterField.effectiveEndDate +
          '&params=' +
          paramsList +
          '&splicingType=' +
          vm.filterField.splicingType +
          '&startDate=' +
          vm.filterField.startDate +
          '&searchDate=' +
          vm.filterField.searchDate +
          '&cleanId=' +
          vm.filterField.cleanId +
          '&field=' +
          fieldArr +
          '&access_token=' +
          localStorage.getItem('access_token')
      } else {
        this.$message({
          type: 'error',
          message: '无数据导出',
        })
      }
    },
    getWashtype() {
      this.axios({
        method: 'post',
        url: 'api-p/project/expand/findwashtype',
      })
        .then((res) => {
          this.washtypeOptions = res.data.result
        })
        .catch((error) => {})
    },
    handleClick(tab) {
      if (tab.name == 'second') {
        var that = this
        that.paramsList.forEach(function (element, index) {
          for (var key in element) {
            if (element.name == '') {
              that.paramsList.splice(index, 1)
            }
          }
        })

        var paramsList = that.packageParams(that.paramsList)
        that.filterField.params = paramsList
        this.axios
          .post('api-s/cs/projectstats/base/projectStats', that.filterField)
          .then((res) => {
            if (!res.data.hasError) {
              const { area, industry, total } = res.data.result
              this.projectTotal = total
              let datas1 = []
              let datas2 = []
              area.forEach((item) => {
                datas1.push([item.areaName, item.amount])
              })
              industry.forEach((item) => {
                datas2.push([item.industryName, item.amount])
              })
              this.$nextTick(() => {
                drarProjectChart('#48A1FF', 'areaChart', datas1)
                drarProjectChart('#03CB94', 'industryChart', datas2)
              })
            }
          })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.container {
  .mainCon {
    // position: absolute;
    top: 197px;
    // left: 24px;
    // right: 24px;
    // bottom: 24px;
    // overflow-y: auto;
    .baseSearch {
      position: relative;
      padding-left: 102px;
      &Title {
        position: absolute;
        top: 0;
        left: 0;
        height: 36px;
        line-height: 36px;
        width: 96px;
        padding-left: 24px;
        display: inline-block;
        font-size: 14px;
        color: #606266;
      }
      &Box {
        margin-left: 10px;
      }
    }
    .proDetailsListBox {
      //   padding-top: 24px;
      padding: 24px 24px 0 24px;
      background: #fff;
      .colSetupBottom {
        margin-bottom: 24px;
        float: left;
        .colSetupBtn {
          float: left;
          margin-right: 20px;
        }
        /deep/ button.el-button.commonBut.saveBtn.funComBut.el-button--default {
          float: right;
        }
      }
    }
  }
  .boxTop {
    margin-top: 24px;
  }

  .loadData/deep/ .el-dialog__header {
    border-bottom: none;
    text-align: center;
  }
  .searchInputWidth .el-input__inner {
    width: 280px;
  }
  /deep/.rangeWidth .el-input__inner {
    width: 70px;
  }

  .chartBox {
    background-color: #fff;
    padding: 24px;
    .chartBoxTotal {
      line-height: 14px;
      font-size: 14px;
      color: #333;
      margin-bottom: 24px;
    }
    .chartTitle {
      line-height: 18px;
      font-size: 16px;
      color: #333;
      font-weight: 700;
      position: relative;
      padding-left: 14px;
    }
    .chartTitle::before {
      position: absolute;
      content: '';
      top: 0;
      bottom: 0;
      width: 4px;
      left: 0;
      background-color: #009588;
    }
  }
}
.eformTitle {
  font-size: 16px;
  width: 96px;
  padding-left: 24px;
  line-height: 16px;
  margin-bottom: 24px;
  color: #3a3a3a;
  font-weight: 700;
}
@import '../../../static/css/filterArea.less';
</style>
